<template>
  <!-- 管理员布局 -->
  <el-container v-if="isAdmin" class="admin-layout">
    <!-- 左侧边栏 -->
    <ManageSider />

    <!-- 右侧内容区 -->
    <el-container direction="vertical">
      <!-- 顶部导航栏 -->
      <ManageHeader />

      <!-- 主内容区 -->
      <el-main class="admin-main-content">
        <div class="admin-container">
          <div class="search-bar">
            <el-input
                v-model="searchName"
                placeholder="请输入用户名"
                style="width: 300px; margin-right: 10px;"
                clearable
            />
            <el-button type="primary" @click="searchUsers">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
          <el-table :data="paginatedUsers" style="width: 100%">
            <el-table-column prop="id" label="用户ID" width="100"></el-table-column>
            <el-table-column prop="name" label="用户名" width="150"></el-table-column>
            <el-table-column prop="telephone" label="电话" width="150"></el-table-column>
            <el-table-column prop="type" label="用户类型" width="100">
              <template #default="{row}">
                {{ row.type }}
              </template>
            </el-table-column>
            <el-table-column prop="date" label="注册时间" width="200"></el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button type="text" @click="openEditUserDialog(scope.row)">修改权限</el-button>
                <el-button type="text" @click="deleteUser(scope.row.id)" style="color: #f56c6c">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
              background
              layout="prev, pager, next"
              :total="users.length"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handlePageChange"
              style="margin-top: 20px;"
          />
        </div>
      </el-main>
    </el-container>
  </el-container>

  <!-- 普通用户布局 -->
  <div v-else>
    <NormalHeader />
    <div class="permission-denied">
      <h1>管理员功能暂时不对您开放</h1>
    </div>
  </div>

  <!-- 修改用户权限的模态框 -->
  <el-dialog v-model="editUserDialogVisible" title="修改用户权限" width="30%">
    <el-form :model="selectedUser" label-width="100px">
      <el-form-item label="用户类型">
        <el-select v-model="selectedUser.type" placeholder="请选择用户类型">
          <el-option label="管理员" value="0"></el-option>
          <el-option label="普通用户" value="1"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editUserDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveUserPermission">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { ElMessage } from "element-plus";
import {getUserList, updateUser, deleteUser, getUserByName} from "@/api";
import NormalHeader from "@/components/NormalHeader.vue";
import ManageSider from "@/components/ManageSider.vue";
import ManageHeader from "@/components/ManageHeader.vue";

export default {
  name: "ManageUser",
  components: {
    NormalHeader,
    ManageSider,
    ManageHeader
  },
  data() {
    return {
      isAdmin: false,
      users: [],
      pageSize: 8,
      currentPage: 1,
      editUserDialogVisible: false,
      selectedUser: { id: null, type: "" },
      searchName: '', // 搜索关键词
    };
  },
  computed: {
    paginatedUsers() {
      if (!Array.isArray(this.users)) return [];
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.users.slice(start, end);
    }
  },
  async mounted() {
    await this.checkAdminPermission();
    if (this.isAdmin) {
      await this.fetchUserList();
    }
  },
  methods: {
    // 搜索
    async searchUsers() {
      try {
        const { data } = await getUserByName(this.searchName);
        this.users = Array.isArray(data?.data?.users) ? data.data.users : [];
        this.currentPage = 1; // 重置到第一页
      } catch (error) {
        ElMessage.error("搜索用户失败");
        console.error(error);
      }
    },
    // 重置方法
    resetSearch() {
      this.searchName = '';
      this.fetchUserList();
    },
    async checkAdminPermission() {
      const userType = localStorage.getItem("type");
      this.isAdmin = userType === "0";
    },
    async fetchUserList() {
      try {
        const { data } = await getUserList();
        this.users = Array.isArray(data?.data?.users) ? data.data.users : [];
      } catch (error) {
        ElMessage.error("获取用户列表失败");
        console.error(error);
        this.users = [];
      }
    },
    openEditUserDialog(user) {
      this.selectedUser = { ...user };
      this.editUserDialogVisible = true;
    },
    async saveUserPermission() {
      try {
        await updateUser(this.selectedUser.id, this.selectedUser.type);
        ElMessage.success("修改成功");
        await this.fetchUserList();
        this.editUserDialogVisible = false;
      } catch (error) {
        ElMessage.error(error.response?.data?.message || "修改失败");
      }
    },
    async deleteUser(userId) {
      try {
        await this.$confirm('确认删除该用户吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        await deleteUser(userId);
        ElMessage.success("删除成功");
        await this.fetchUserList();
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error("删除失败");
        }
      }
    },
    handlePageChange(page) {
      this.currentPage = page;
    }
  }
};
</script>

<style scoped>
.admin-layout {
  height: 100vh;
}

.admin-main-content {
  padding: 20px 20px 20px;
  height: calc(100vh - 67px);
  overflow-y: auto;
  margin-left: 200px; /* 等于侧边栏宽度 */
  background-color: #f5f7fa;
}

.admin-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.permission-denied {
  text-align: center;
  padding: 100px 0;
}

/* 优化表格样式 */
.el-table {
  margin-top: 20px;
}
.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}
/* 响应式调整 */
@media (max-width: 992px) {
  .admin-container {
    padding: 15px;
  }
}
</style>
